<template>
  <div class="page">
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @cancel="$router.back()"
    />

    <div class="list">
      <van-cell-group>
        <van-cell
          v-for="item in displayCinemas"
          :key="item.cinemaId"
          :title="item.name"
          :value="item.districtName"
          :label="item.address"
          @click="jumpDetailByCinema(item)"
        />
      </van-cell-group>

      <FancySection v-show="!keyword" :list="displayRecommendList" @click="jumpDetail" />
      <FancySection v-show="!keyword" title="历史搜索" v-model:list="historyList" closeable />

      <div class="empty" v-if="keyword && displayCinemas.length === 0">
        <van-empty description="暂无数据" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FancySection, { type FancySectionItem } from '@/components/fancy-section/index.vue'
import { ref, computed, watch, watchEffect } from 'vue'
import store2 from 'store2'
import { useStore } from '@/hooks'

// import { type Cinema } from '@/api/interface'

import { type Cinema, getCinemaListRecommend } from '@/api'

// const cinemasHistoryList = window.sessionStorage.getItem('cinemas-history-list')

const { cityStore, cinemaStore } = useStore()

// 离你最近
const recommendList = ref<Cinema.Item[]>([])
// 历史搜索
const historyList = ref<FancySectionItem[]>(store2.session.get('cinemas-history-list') || [])
// 监听历史搜索数据的变化，写入本地存储
watch(historyList, (newValue) => {
  // window.sessionStorage.setItem('cinemas-history-list', JSON.stringify(newValue))
  store2.session.set('cinemas-history-list', newValue)
})

// 搜索关键字
const keyword = ref('')
const displayCinemas = computed(() => {
  if (!keyword.value) {
    return []
  }

  return cinemaStore.items.filter((item) => item.name.includes(keyword.value))
})
const displayRecommendList = computed(() => {
  return recommendList.value
    .map((item) => ({
      id: item.cinemaId,
      text: item.name
    }))
    .splice(0, 5)
})

watchEffect(() => {
  cinemaStore.getItems({ cityId: cityStore.curCityId!, ticketFlag: 0 })

  getCinemaListRecommend({ cityId: cityStore.curCityId }).then((result) => {
    recommendList.value = result.cinemas
  })
})

/**
 * 离你最近，点击
 */
function jumpDetail(data: FancySectionItem) {
  historyList.value.unshift(data)
  historyList.value = historyList.value.splice(0, 2)
}

/**
 * 搜索列表，点击
 */
function jumpDetailByCinema(data: Cinema.Item) {
  // 1. 将当前点击的 影院 写入到 historyList 中
  historyList.value.unshift({ id: data.cinemaId, text: data.name })
  historyList.value = historyList.value.splice(0, 2)
  // 2. 本地存储
  // window.sessionStorage.setItem('cinemas-history-list', JSON.stringify(historyList.value))

  // TODO. 跳转页面
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.list {
  flex: 1;
  overflow-y: auto;
}
</style>
